import { api } from '../../utils/api';

Page({
  data: {
    pendingRequests: [] as any[],
    loading: false,
    statusBarHeight: 0,
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0,
    });
    this.loadPendingRequests();
  },

  onShow() {
    this.loadPendingRequests();
  },

  async loadPendingRequests() {
    this.setData({
      loading: true,
    });

    try {
      const res: any = await api.getPendingRequests();
      if (res.success && res.requests) {
        // 获取请求者详细信息
        const requestsWithInfo = res.requests.map((request: any) => {
          // 这里应该调用获取用户信息的接口
          // 暂时使用userId作为显示
          // 确保requestUser始终有值，避免WXML访问undefined
          return {
            ...request,
            requestUser: {
              id: request.userId,
              nickname: `用户${request.userId}`,
              avatar: '',
            },
          };
        });

        this.setData({
          pendingRequests: requestsWithInfo,
        });
      }
    } catch (error) {
      console.error('加载好友请求失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
    } finally {
      this.setData({
        loading: false,
      });
    }
  },

  async onAcceptRequest(e: any) {
    const requestId = e.currentTarget.dataset.requestid;
    
    wx.showLoading({
      title: '处理中...',
    });

    try {
      const res: any = await api.acceptContactRequest(requestId);
      if (res.success) {
        wx.hideLoading();
        wx.showToast({
          title: '已同意',
          icon: 'success',
        });
        // 重新加载列表
        this.loadPendingRequests();
        // 通知通讯录页面更新计数（如果使用事件通信）
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message || '操作失败',
          icon: 'none',
        });
      }
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none',
      });
    }
  },

  onRejectRequest() {
    
    wx.showModal({
      title: '提示',
      content: '确定要拒绝这个好友请求吗？',
      success: async (res) => {
        if (res.confirm) {
          // 这里可以调用拒绝接口，暂时简化处理
          wx.showToast({
            title: '已拒绝',
            icon: 'success',
          });
          this.loadPendingRequests();
        }
      },
    });
  },

  formatTime(timestamp: any) {
    if (!timestamp) return '';
    
    // 处理字符串格式 "yyyy-MM-dd HH:mm:ss" 或 ISO 格式
    let date: Date;
    if (typeof timestamp === 'string') {
      // 如果包含空格，说明是 "yyyy-MM-dd HH:mm:ss" 格式
      if (timestamp.includes(' ')) {
        // 将 "yyyy-MM-dd HH:mm:ss" 转换为标准格式
        date = new Date(timestamp.replace(' ', 'T') + ':00');
      } else {
        date = new Date(timestamp);
      }
    } else {
      date = new Date(timestamp);
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '';
    }
    
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const msgDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const diff = today.getTime() - msgDate.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      const hours = date.getHours();
      const minutes = date.getMinutes();
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      return `周${weekDays[date.getDay()]}`;
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}/${day}`;
    }
  },

  onBack() {
    wx.navigateBack();
  },

  onAddFriend() {
    // 跳转到二维码扫描页面添加好友
    wx.navigateTo({
      url: '/pages/qrcode/qrcode?action=scan',
    });
  },
});

